package com.training.java.redbox;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import com.training.java.redbox.domain.Customer;
import com.training.java.redbox.domain.CustomerDAO;
import com.training.java.redbox.domain.CustomerDaoJdbcImpl;
import com.training.java.redbox.domain.DAOException;

public class SignupAction extends DispatchAction {
	
	public ActionForward redirect(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		return mapping.findForward("signup");
	}
	
	
	
	public ActionForward submit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		CustomerForm customerForm = (CustomerForm)form;
		
		CustomerDAO dao = new CustomerDaoJdbcImpl();
		
		Customer customer = dao.findCustomerByUsername(customerForm.getUserName());
		
		if(customer==null){
			
			customer = new Customer(0, customerForm.getFirstName(), customerForm.getLastName());
			customer.setAddress(customerForm.getAddress());
			customer.setCity(customerForm.getCity());
			customer.setState(customerForm.getState());
			customer.setZipCode(customerForm.getZipCode());
			customer.setUserName(customerForm.getUserName());
			customer.setPassword(customerForm.getPassword());
			
			dao.addCustomer(customer);
		
			return mapping.findForward("login");

		
		}else{
			
			ActionErrors errors = new ActionErrors();			
			errors.add("username.error", new ActionMessage("username.exists"));
			
			saveErrors(request, errors);	
			
			return mapping.findForward("signup");
			
		}
		
		
	}

}
